import { ref } from "vue";
import FiledProperty from "@/models/FiledProperty";
import { stringDateFormat } from "@/utils/stingTodate";

export default function ImportFormDialogEvent(props: {
  filedPropertyList: Array<FiledProperty>;
}) {
  // 批量导入窗口的显示状态
  const importFormVisible = ref(false);
  const { DateFormat } = stringDateFormat();
  // 改变批量导入窗口的显示状态.
  const changeImportFormVisible = () => {
    importFormVisible.value = !importFormVisible.value;
  };

  // 批量导入数据格式化
  const submitJsonFormat = (
    data: Record<string, unknown>[][],
    callback: (
      value: Record<string, unknown>[],
      isSuccessFormat: boolean
    ) => void
  ) => {
    let breakFlag = false;
    const jsonList: Record<string, unknown>[] = [];
    for (let i = 0; i < data[0].length && !breakFlag; i++) {
      jsonList[i] = {};
      try {
        props.filedPropertyList.forEach((item) => {
          jsonList[i][item.filedName] = data[0][i][item.label];
          if (
            item.filedName !== "ID" &&
            item.rules != undefined &&
            jsonList[i][item.filedName] === undefined
          ) {
            breakFlag = true;
            throw new Error("转化异常");
          }
          if (
            item.formType == "el-form-picker-date" &&
            jsonList[i][item.filedName]
          ) {
            console.log(jsonList[i][item.filedName]);
            jsonList[i][item.filedName] = DateFormat(
              jsonList[i][item.filedName] as string
            );
          }
          if (item.formatter) {
            if (item.formatter.boolean) {
              item.formatter.boolean.forEach(
                (boolean: Record<string, unknown>) => {
                  if (boolean.label == jsonList[i][item.filedName]) {
                    jsonList[i][item.filedName] = boolean.value;
                  }
                }
              );
            } else if (item.formatter.string) {
              item.formatter.string.forEach(
                (string: Record<string, unknown>) => {
                  if (string.label == jsonList[i][item.filedName]) {
                    jsonList[i][item.filedName] = string.value;
                  }
                }
              );
            } else if (item.formatter.number) {
              item.formatter.number.forEach(
                (number: Record<string, unknown>) => {
                  if (number.label == jsonList[i][item.filedName]) {
                    jsonList[i][item.filedName] = number.value;
                  }
                }
              );
            }
          }
        });
        jsonList[i].createUser = sessionStorage.getItem("userName") as string;
        jsonList[i].createGmt = new Date();
      } catch (e) {
        console.log(e);
      }
    }
    if (!breakFlag) {
      callback(jsonList, true);
    } else {
      callback([], false);
    }
  };
  return {
    importFormVisible,
    changeImportFormVisible,
    submitJsonFormat,
  };
}
